import type { Dayjs } from 'dayjs';

import type { SysRoleReq } from '#/type/sys_role';

import type { Reactive } from 'vue';

export default function useFormHook(
  fetchTableData: () => Promise<void> | void,
  formSearch: Reactive<SysRoleReq>,
  tablePagination: Reactive<Record<string, any>>,
) {
  const formSearchSubmit = () => {
    fetchTableData();
  };
  const formSearchReset = () => {
    // 重置表单数据
    const keys = Object.keys(formSearch) as (keyof SysRoleReq)[];
    for (const key of keys) {
      formSearch[key] = undefined as any;
    }
    tablePagination.current = 1;
    tablePagination.pageSize = 10;
    fetchTableData();
  };
  const formInputClear = (key: keyof SysRoleReq, e: Event) => {
    if ((e.target as HTMLInputElement).value === '') {
      formSearch[key] = undefined as any;
      fetchTableData();
    }
  };
  const formSelectClear = (key: keyof SysRoleReq, e: any) => {
    if (e === undefined || (Array.isArray(e) && e.length === 0)) {
      formSearch[key] = undefined as any;
      fetchTableData();
    }
  };

  const formDateRangeClear = (
    key: keyof SysRoleReq,
    dates: [Dayjs, Dayjs] | [string, string],
    dateStrings: [string, string],
  ) => {
    if (
      dates === null ||
      dateStrings === null ||
      dateStrings[0] === '' ||
      dateStrings[1] === ''
    ) {
      formSearch[key] = undefined as any;
      fetchTableData();
    }
  };
  return {
    formSearchSubmit,
    formSearchReset,
    formInputClear,
    formSelectClear,
    formDateRangeClear,
  };
}
